import 'package:flutter/material.dart';
import 'ServiceItem.dart';
import 'package:flutter/services.dart';
import 'package:flutter_wisave/Tools/NetworkService.dart';
import '../widgets/AppColors.dart';

class ServicePage extends StatefulWidget {
  const ServicePage({super.key});

  @override
  State<ServicePage> createState() => _ServicePageState();
}

class _ServicePageState extends State<ServicePage>
    with TickerProviderStateMixin {
  final NetworkService _networkService = NetworkService();
  late TabController _tabController;
  List<dynamic> typeListData = [];

  @override
  void initState() {
    super.initState();
    _networkService.setupInterceptors(context);
    _tabController = TabController(length: 0, vsync: this);
    _loadData();
  }

  Future<void> _loadData() async {
    try {
      final result = await _fetchData();
      if (result != null && result['rows'] != null) {
        setState(() {
          typeListData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          _tabController.dispose(); // 先释放之前的控制器
          _tabController =
              TabController(length: typeListData.length, vsync: this);
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchData() async {
    try {
      final response =
          await _networkService.get('/plcTimer/centre/selectTypeList');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  Future<void> _loadListData() async {
    try {
      final result = await _fetchListData();
      if (result != null && result['rows'] != null) {
        setState(() {
          typeListData = (result['rows'] as List)
              .map((item) => (item as Map<String, dynamic>))
              .toList();
          _tabController.dispose(); // 先释放之前的控制器
          _tabController =
              TabController(length: typeListData.length, vsync: this);
        });
      } else {
        print('No data received from _fetchData');
      }
    } catch (e) {
      print('Error in _loadData: $e');
    }
  }

  Future<Map<String, dynamic>?> _fetchListData() async {
    try {
      final response =
          await _networkService.get('/plcTimer/centre/selectListByType');
      if (response.statusCode == 200) {
        return response.data;
      } else {
        print('Failed to load data: ${response.statusCode}');
        return null;
      }
    } catch (e) {
      print('Error in _fetchData: $e');
      return null;
    }
  }

  @override
  Widget build(BuildContext context) {
    SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.transparent, // 状态栏颜色
    ));

    return Scaffold(
      backgroundColor: AppColors.backgroundColor,
      appBar: AppBar(
        title: const Text('服务中心'),
        foregroundColor: AppColors.textPrimary,
        backgroundColor: Colors.transparent,
        flexibleSpace: Container(
          decoration: const BoxDecoration(
            image: DecorationImage(
              image: AssetImage('assets/images/home/home_topbg.png'),
              fit: BoxFit.cover,
            ),
          ),
        ),
        bottom: PreferredSize(
          preferredSize: const Size.fromHeight(48),
          child: Container(
            decoration: const BoxDecoration(
              color: Colors.transparent,
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(20),
                topRight: Radius.circular(20),
              ),
            ),
            child: TabBar(
              isScrollable: false,
              indicatorColor: Colors.blue,
              indicatorWeight: 2,
              indicatorPadding: const EdgeInsets.only(right: 50, left: 50),
              indicatorSize: TabBarIndicatorSize.tab,
              labelColor:
                  AppColors.textPrimary, //TDTheme.of(context).grayColor12,
              unselectedLabelColor:
                  AppColors.textSecondary, //TDTheme.of(context).grayColor8,
              labelStyle:
                  const TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
              unselectedLabelStyle: const TextStyle(fontSize: 16),
              controller: _tabController,
              tabs: [
                for (var item in typeListData)
                  Tab(child: Text(item['dictLabel'])),
              ],
            ),
          ),
        ),
      ),
      body: TabBarView(
        controller: _tabController,
        children: [
          ListView(
            children: [
              // 列表
              Expanded(
                child: ListView.builder(
                  itemCount: 6,
                  shrinkWrap: true, // 适应内容高度
                  physics: const NeverScrollableScrollPhysics(), // 禁止滚动
                  itemBuilder: (context, index) {
                    return Padding(
                      padding:
                          const EdgeInsets.symmetric(vertical: 0.0), // 设置行间距为1
                      child: GestureDetector(
                        // 添加点击事件
                        onTap: () {},
                        child: const ServiceItem(),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
          ListView(
            children: [
              // 列表
              Expanded(
                child: ListView.builder(
                  itemCount: 6,
                  shrinkWrap: true, // 适应内容高度
                  physics: const NeverScrollableScrollPhysics(), // 禁止滚动
                  itemBuilder: (context, index) {
                    return Padding(
                      padding:
                          const EdgeInsets.symmetric(vertical: 0.0), // 设置行间距为1
                      child: GestureDetector(
                        // 添加点击事件
                        onTap: () {},
                        child: const ServiceItem(),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
          ListView(
            children: [
              // 列表
              Expanded(
                child: ListView.builder(
                  itemCount: 6,
                  shrinkWrap: true, // 适应内容高度
                  physics: const NeverScrollableScrollPhysics(), // 禁止滚动
                  itemBuilder: (context, index) {
                    return Padding(
                      padding:
                          const EdgeInsets.symmetric(vertical: 0.0), // 设置行间距为1
                      child: GestureDetector(
                        // 添加点击事件
                        onTap: () {},
                        child: const ServiceItem(),
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }
}
